package test;

import java.util.*;

/**
 * 描述：
 *      移掉k位数字
 * @author hl
 * @version 1.0
 * @date 2020/11/15 9:29
 */
public class RemoveKdigits {
    public String removeKdigits2(String num, int k) {
        if(num.length() == k){
            return "0";
        }
        Deque<Character> deque = new LinkedList<>();
        for (int i = 0; i < num.length(); i++) {
            while (!deque.isEmpty() && num.charAt(i) < deque.peekLast() && k-- > 0) {
                deque.pop();
            }
            deque.offerLast(num.charAt(i));
        }
        for (int i = k; i > 0; i--) {
            deque.pollLast();
        }
        StringBuilder res = new StringBuilder();
        boolean flag = true;
        while(!deque.isEmpty()){
            char temp = deque.pollFirst();
            if (flag && temp == 0) {
                continue;
            }
            res.append(temp);
            flag = false;
        }
        return res.length() == 0 ? "0" : res.toString();
    }
    public String removeKdigits(String num, int k) {
        if (num.length() == k) {
            return "0";
        }
        char[] chs = num.toCharArray();
        List<Integer> list = new ArrayList<>();
        for (int i = 0; i < chs.length; i++) {
            list.add(chs[i] - '0');
        }
        for (int i = 0; i < k; i++) {
            for (int j = 0; j < list.size(); j++) {
                if (j == list.size() - 1 ||  list.get(j) > list.get(j + 1)) {
                    list.remove(j);
                    break;
                }
            }
        }
        while(list.size() > 1 && list.get(0).equals(0)){
            list.remove(0);
        }
        StringBuilder res = new StringBuilder();
        list.forEach(integer -> res.append(integer));
        return res.toString();
    }

    public static void main(String[] args) {
        System.out.println(new RemoveKdigits().removeKdigits("1432219", 3));
    }

}
